// pages/shoporder/shoporder.js
var util = require('../../../utils/util.js');
var textspeech=require('../../../utils/textspeech.js')
let socketOpen = false
var socketMsgQueue = []
Page({
  data: {
    msg: 'www',
    currentTab: -1,
    orderstate: '-1',
    orders: [],
    remindorders:[],//预定订单，到时自动提醒
    pagenum: 1,
    pagesize: 10,
    states: [],
    //提前提醒时间 （分）
    advanceTime:10,
 
  },
  onLoad: function(options) {
    
  },
  onShow:function(){
    this.setOrder();
    this.setstatename();
    this.getneworder();
    this.setData({ currentTab: 0, orderstate: 0 })
    this.timetoremind();
  },
  sendSocketMessage: function() {
    var msg = this.data.msg;
    if (socketOpen) {
      wx.sendSocketMessage({
        data: msg
      })
    } else {
      socketMsgQueue.push(msg)
    }
  },
  setOrder: function() {
    var that = this
    util.fetchGet(

      util.url.shop_order_list + "?date=",
      function(ret) {
        var list = ret.data;
        that.setOrderToData(list);
      }
    )
  },
  sortFun:function(a,b){   
      if (b.fetchTime > a.fetchTime) {
        return 1;
      } else {
        return -1
      }   
  },
  //从新排序后放入订单列表
  setOrderToData:function(list){
    var that=this;
    var iswill=false;
    if (list.length > 0) {
      //已完成最下，根据fetchtime 排序  未到取餐时间的放在下面
      var list0=[];
      var list1=[];
      var list2=[];
      var now = util.getNextTime(that.data.advanceTime);
      for (var i=0;i<list.length;i++){
        if (list[i].foodstate==2){
          list2.push(list[i]);
        }else{
          var fetchTime = list[i].fetchTime;
          
          if (fetchTime<now){
            list0.push(list[i])
          }else{
            list1.push(list[i]); 
            iswill=true;           
          }
        }
      }
      list0.sort(that.sortFun);
      list1.sort(that.sortFun);
      list2.sort(that.sortFun)
      
      list=list0.concat(list1).concat(list2);
      that.setData({
        orders: list,
        remindorders: list1
      })
    }
  },
  setstatename: function() {
    var that = this
    util.fetchGet(
      util.url.shop_order_orderstate,
    //  'myshop/getfoodstate?',
      function(ret) {
        var map = ret.data;
        var states = [];
        for (var p in map) {
          var state = {
            "name": map[p],
            "id": p
          };
          states.push(state);
        }
        that.setData({
          states: states
        })
        console.log(ret);
      }
    )
  },
  makefood: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var url = util.url.shop_order_makefood + "?id=" + id;
    util.fetchGet(
      url,
      function(ret) {
        console.log(ret);
        that.updateOrderState(id, 1);
      }
    )
  },
  takefood: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var url = util.url.shop_order_takefood + "?id=" + id;
    util.fetchGet(
      url,
      function(ret) {
        console.log(ret);
        that.updateOrderState(id, 2);
      }
    )
  },

  updateOrderState: function(id, state) {
    var orders = this.data.orders;
    for (var i = 0; i < orders.length; i++) {
      if (orders[i].id == id) {
        orders[i].foodstate = state;
        var states = this.data.states;
        for (var j = 0; j < states.length; j++) {
          if (states[j].id == state) {
            orders[i].stateName = states[j].name;
          }
        }
      }
    }
    this.setData({
      orders: orders
    })
  },

  // order
  orderOk: function() {
    this.setData({
      orderOk: true
    })
  },
  okCancel: function() {
    this.setData({
      orderOk: false
    })
  },
  swichNav: function(e) {

    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current,
        orderstate: e.target.dataset.current
      })
    }
  },

  //定时查看是否有新订单
  getneworder:function(){
    var that=this;
    var neworder=function(){
      var msgs=wx.getStorageSync("message");
     // console.log(msgs);
      if (msgs && msgs.length>0){
        var id=msgs[0];
        msgs.splice(0, 1);
        var orders = that.data.orders;
        var inline = false;
        for (var i = 0; i < orders.length; i++) {
          if (orders[i].id == id) {
            inline = true;
          }
        }
        if (!inline) return ;
        var url = util.url.shop_order_id + "?id=" + id;
        util.fetchGet(
          url,
          function(ret){
            
            orders.push(ret.data)
            that.setOrderToData(orders);            
            wx.setStorageSync("message", msgs);
          }
        )
      }
    } 
    var Interval = setInterval(neworder,10000);
     
  },
  timetoremind:function(){
    var that=this;
    var listremind=function(){
      var remindorders = that.data.remindorders;
      if (remindorders.length > 0) {
        var now = util.getNextTime(that.data.advanceTime);
        var isupdate=false; 
        for (var i = 0; i < remindorders.length;i++){
          if (now >= remindorders[i].fetchTime){
            console.log(remindorders[i]);//提醒
            textspeech.speech("你有订单还有10分钟就要取餐啦，请及时出餐");
            remindorders.splice(i,1);
            isupdate=true;
          }
        }
        if (isupdate){
          that.setOrderToData(that.data.orders);
        }
      }
    }
    var Interval = setInterval(listremind,30000)
    
  },
  addTips:function(e){
    var oid=e.currentTarget.dataset.id;
    var url = util.url.shop_order_addtips;
    url+="?id="+oid+"&tips="+100
    util.fetchGet(
      url,
      function(ret){
        console.log(ret);
      }
    )
  },
  refusedOrder:function(e){
    var oid = e.currentTarget.dataset.id;
    var url = util.url.shop_order_refused;
    url += "?id=" + oid 
    util.fetchGet( 
      url,
      function (ret) {
        console.log(ret);
      }
    )
  }
}) 